<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cesium 高性能图标展示 - 带背景的文字广告牌</title>
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.109/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.109/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        html, body, #cesiumContainer {
            width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        #controlPanel {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(42, 42, 42, 0.9);
            padding: 15px;
            border-radius: 8px;
            color: white;
            z-index: 1000;
            max-width: 300px;
            backdrop-filter: blur(5px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }

        h1 {
            margin: 0 0 15px 0;
            font-size: 18px;
            color: #48b6ff;
            border-bottom: 1px solid #444;
            padding-bottom: 8px;
        }

        .button-group {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
        }

        button {
            background: #48b6ff;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            flex: 1;
            font-weight: 500;
            transition: all 0.2s;
        }

        button:hover {
            background: #2a9de9;
            transform: translateY(-1px);
        }

        button:active {
            transform: translateY(1px);
        }

        button:disabled {
            background: #666;
            cursor: not-allowed;
            transform: none;
        }

        .stats {
            margin-top: 12px;
            font-size: 13px;
            color: #ccc;
            line-height: 1.4;
        }

        .loading {
            display: none;
            color: #48b6ff;
            font-style: italic;
        }

        .success {
            color: #4CAF50;
            font-weight: bold;
        }

        .performance {
            background: rgba(0, 0, 0, 0.5);
            padding: 8px;
            border-radius: 4px;
            margin-top: 8px;
        }

        #infoBox {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(42, 42, 42, 0.9);
            padding: 15px;
            border-radius: 8px;
            color: white;
            z-index: 1000;
            max-width: 300px;
            display: none;
        }

        .toggle-group {
            display: flex;
            margin: 8px 0;
        }

        .toggle-btn {
            flex: 1;
            padding: 6px;
            font-size: 12px;
            background: #555;
        }

        .toggle-btn.active {
            background: #48b6ff;
        }

        .background-options {
            margin: 8px 0;
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
        }

        .bg-option {
            width: 20px;
            height: 20px;
            border-radius: 3px;
            cursor: pointer;
            border: 2px solid transparent;
        }

        .bg-option.active {
            border-color: white;
        }
    </style>
</head>
<body>
<div id="cesiumContainer"></div>

<div id="controlPanel">
    <h1>Cesium 图标+文字广告牌</h1>

    <div class="button-group">
        <button id="addIcons">添加10000个图标</button>
        <button id="clearIcons">清除所有图标</button>
    </div>

    <div class="button-group">
        <button id="addSingleIcon">添加单个图标</button>
        <button id="flyToIcons">飞行到图标区域</button>
    </div>

    <div class="toggle-group">
        <button id="toggleIcons" class="toggle-btn active">显示图标</button>
        <button id="toggleLabels" class="toggle-btn active">显示广告牌</button>
    </div>

    <div>
        <div style="font-size: 12px; margin-bottom: 4px;">文字样式:</div>
        <div class="background-options">
            <div class="bg-option active" style="background: #000000;" data-color="#000000"></div>
            <div class="bg-option" style="background: #2a2a2a;" data-color="#2a2a2a"></div>
            <div class="bg-option" style="background: #4CAF50;" data-color="#4CAF50"></div>
            <div class="bg-option" style="background: #2196F3;" data-color="#2196F3"></div>
            <div class="bg-option" style="background: #9C27B0;" data-color="#9C27B0"></div>
            <div class="bg-option" style="background: #FF5722;" data-color="#FF5722"></div>
            <div class="bg-option" style="background: #FFC107;" data-color="#FFC107"></div>
            <div class="bg-option" style="background: #009688;" data-color="#009688"></div>
        </div>
    </div>

    <div class="stats">
        <div>图标数量: <span id="iconCount">0</span></div>
        <div class="loading" id="loadingStatus">正在生成图标，请稍候...</div>
        <div id="successStatus"></div>

        <div class="performance">
            <div>性能提示:</div>
            <div>• 使用BillboardCollection高效渲染</div>
            <div>• 双层文字实现背景效果</div>
            <div>• 可自定义文字颜色</div>
        </div>
    </div>
</div>

<div id="infoBox">
    <h3>图标信息</h3>
    <div id="infoContent"></div>
    <button onclick="document.getElementById('infoBox').style.display = 'none'">关闭</button>
</div>

<script>
    // 设置Cesium Ion访问令牌

    Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNWY1NDhkNy00NDI4LTQyZWQtYTRmNS1iNGQ0MjMxNDIzZWMiLCJpZCI6MTU0NDA1LCJpYXQiOjE2ODk1NzY0ODl9.1zt09SfJKVhZNs-zzn3fN5pzpkrYEzatuDTZYviZx1I";

    // 初始化Cesium Viewer
    const viewer = new Cesium.Viewer('cesiumContainer', {
        terrain: Cesium.Terrain.fromWorldTerrain(),
        timeline: false,
        animation: false,
        sceneModePicker: false,
        baseLayerPicker: false,
        geocoder: false,
        homeButton: false,
        fullscreenButton: false,
        vrButton: false,
        navigationHelpButton: false,
        selectionIndicator: false,
        infoBox: false
    });

    // 设置初始视角
    viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(116.39, 39.91, 1000000),
        orientation: {
            heading: 0,
            pitch: -1.57,
            roll: 0
        }
    });

    // 高性能图标管理器
    class HighPerformanceBillboardManager {
        constructor(viewer) {
            this.viewer = viewer;
            this.billboardCollection = null;
            this.labelCollection = null;
            this.backgroundLabelCollection = null;
            this.iconCount = 0;
            this.billboardData = new Map();
            this.showIcons = true;
            this.showLabels = true;
            this.currentTextColor = Cesium.Color.WHITE;
            this.currentBackgroundColor = Cesium.Color.BLACK;

            // 设置拾取事件
            this.setupPicking();
        }

        // 批量添加图标和广告牌
        async addBillboardsBatch(billboardsData) {
            const startTime = performance.now();

            // 清除现有图标
            this.clearBillboards();

            // 创建图标集合
            this.billboardCollection = new Cesium.BillboardCollection({
                scene: this.viewer.scene
            });

            // 创建文字标签集合（前景文字）
            this.labelCollection = new Cesium.LabelCollection({
                scene: this.viewer.scene
            });

            // 创建背景文字集合（模拟背景效果）
            this.backgroundLabelCollection = new Cesium.LabelCollection({
                scene: this.viewer.scene
            });

            // 添加到场景
            this.viewer.scene.primitives.add(this.billboardCollection);
            this.viewer.scene.primitives.add(this.backgroundLabelCollection);
            this.viewer.scene.primitives.add(this.labelCollection);

            // 批量创建图标和标签
            billboardsData.forEach((data, index) => {
                this.createBillboardWithLabel(data, index);
            });

            this.iconCount = billboardsData.length;

            const endTime = performance.now();
            return {
                time: (endTime - startTime).toFixed(2),
                count: billboardsData.length
            };
        }

        createBillboardWithLabel(data, index) {
            const position = Cesium.Cartesian3.fromDegrees(
                data.longitude,
                data.latitude,
                data.height || 0
            );

            const id = `billboard-${index}`;

            // 创建图标
            const billboard = this.billboardCollection.add({
                position: position,
                image: this.createSVGDataUrl(data.color, data.iconText),
                scale: 0.5,
                width: 32,
                height: 32,
                id: id,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, 0),
                show: this.showIcons
            });

            // 创建背景文字（模拟背景效果）
            const backgroundLabel = this.backgroundLabelCollection.add({
                position: position,
                text: data.name,
                font: 'bold 14px Arial',
                fillColor: this.currentBackgroundColor,
                outlineColor: this.currentBackgroundColor,
                outlineWidth: 8, // 粗边框模拟背景
                pixelOffset: new Cesium.Cartesian2(0, -35),
                verticalOrigin: Cesium.VerticalOrigin.TOP,
                heightReference: Cesium.HeightReference.NONE,
                show: this.showLabels,
                id: id + '-bg',
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                scale: 1.0
            });

            // 创建前景文字
            const foregroundLabel = this.labelCollection.add({
                position: position,
                text: data.name,
                font: 'bold 12px Arial',
                fillColor: this.currentTextColor,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 1,
                pixelOffset: new Cesium.Cartesian2(0, -35),
                verticalOrigin: Cesium.VerticalOrigin.TOP,
                heightReference: Cesium.HeightReference.NONE,
                show: this.showLabels,
                id: id + '-fg',
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                scale: 0.9
            });

            // 存储图标数据
            this.billboardData.set(id, {
                data: data,
                billboard: billboard,
                backgroundLabel: backgroundLabel,
                foregroundLabel: foregroundLabel
            });
        }

        createSVGDataUrl(color, text) {
            const svg = `
                    <svg width="32" height="32" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="16" cy="16" r="14" fill="${color}" stroke="white" stroke-width="2"/>
                        <text x="16" y="20" text-anchor="middle" fill="white" font-size="12" font-weight="bold">${text || '!'}</text>
                    </svg>
                `;
            return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
        }

        // 更新所有文字广告牌的颜色
        updateLabelColors(backgroundColor, textColor = Cesium.Color.WHITE) {
            this.currentBackgroundColor = backgroundColor;
            this.currentTextColor = textColor;

            if (this.backgroundLabelCollection && this.labelCollection) {
                // 更新背景文字
                this.backgroundLabelCollection.forEach(label => {
                    label.fillColor = backgroundColor;
                    label.outlineColor = backgroundColor;
                });

                // 更新前景文字
                this.labelCollection.forEach(label => {
                    label.fillColor = textColor;
                });
            }
        }

        // 添加单个图标和广告牌
        addSingleBillboard(data) {
            if (!this.billboardCollection) {
                this.billboardCollection = new Cesium.BillboardCollection({
                    scene: this.viewer.scene
                });
                this.viewer.scene.primitives.add(this.billboardCollection);
            }

            if (!this.labelCollection) {
                this.labelCollection = new Cesium.LabelCollection({
                    scene: this.viewer.scene
                });
                this.viewer.scene.primitives.add(this.labelCollection);
            }

            if (!this.backgroundLabelCollection) {
                this.backgroundLabelCollection = new Cesium.LabelCollection({
                    scene: this.viewer.scene
                });
                this.viewer.scene.primitives.add(this.backgroundLabelCollection);
            }

            this.createBillboardWithLabel(data, this.iconCount);
            this.iconCount++;
        }

        // 设置拾取功能
        setupPicking() {
            const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

            handler.setInputAction((event) => {
                const picked = this.viewer.scene.pick(event.position);
                if (Cesium.defined(picked) && picked.id) {
                    const billboardId = picked.id;
                    const item = this.billboardData.get(billboardId);
                    if (item) {
                        this.showPickedInfo(item.data);
                    }
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }

        showPickedInfo(data) {
            const infoBox = document.getElementById('infoBox');
            const infoContent = document.getElementById('infoContent');

            infoContent.innerHTML = `
                    <div><strong>名称:</strong> ${data.name}</div>
                    <div><strong>经度:</strong> ${data.longitude.toFixed(4)}</div>
                    <div><strong>纬度:</strong> ${data.latitude.toFixed(4)}</div>
                    <div><strong>高度:</strong> ${(data.height || 0).toFixed(0)} 米</div>
                    <div style="display: flex; align-items: center; margin-top: 8px;">
                        <strong>颜色:</strong>
                        <div style="width: 16px; height: 16px; background: ${data.color}; margin-left: 8px; border-radius: 3px;"></div>
                    </div>
                    <div><strong>图标文字:</strong> ${data.iconText}</div>
                `;

            infoBox.style.display = 'block';
        }

        // 切换图标显示状态
        toggleIconsVisibility(show) {
            this.showIcons = show;
            if (this.billboardCollection) {
                this.billboardCollection.forEach(billboard => {
                    billboard.show = show;
                });
            }
        }

        // 切换广告牌显示状态
        toggleLabelsVisibility(show) {
            this.showLabels = show;
            if (this.labelCollection) {
                this.labelCollection.forEach(label => {
                    label.show = show;
                });
            }
            if (this.backgroundLabelCollection) {
                this.backgroundLabelCollection.forEach(label => {
                    label.show = show;
                });
            }
        }

        // 清除所有图标和广告牌
        clearBillboards() {
            if (this.billboardCollection) {
                this.viewer.scene.primitives.remove(this.billboardCollection);
                this.billboardCollection = null;
            }
            if (this.labelCollection) {
                this.viewer.scene.primitives.remove(this.labelCollection);
                this.labelCollection = null;
            }
            if (this.backgroundLabelCollection) {
                this.viewer.scene.primitives.remove(this.backgroundLabelCollection);
                this.backgroundLabelCollection = null;
            }
            this.billboardData.clear();
            this.iconCount = 0;

            // 隐藏信息框
            document.getElementById('infoBox').style.display = 'none';
        }

        // 获取图标数量
        getIconCount() {
            return this.iconCount;
        }
    }

    // 生成测试数据
    function generateTestData(count) {
        const data = [];
        const colors = [
            '#FF5252', '#FF4081', '#E040FB', '#7C4DFF',
            '#536DFE', '#448AFF', '#40C4FF', '#18FFFF',
            '#64FFDA', '#69F0AE', '#B2FF59', '#EEFF41',
            '#FFFF00', '#FFD740', '#FFAB40', '#FF6E40'
        ];

        const icons = ['🏠', '🏢', '🏣', '🏤', '🏥', '🏦', '🏨', '🏩', '🏪', '🏫', '🏬', '🏭', '🏯', '🏰'];
        const locations = ['北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '武汉', '西安', '南京'];

        for (let i = 0; i < count; i++) {
            const locationIndex = i % locations.length;
            data.push({
                longitude: 116.39 + (Math.random() * 10 - 5),  // 北京周边±5度
                latitude: 39.91 + (Math.random() * 10 - 5),    // 北京周边±5度
                height: Math.random() * 5000,
                color: colors[i % colors.length],
                iconText: icons[i % icons.length],
                name: `${locations[locationIndex]} - 地点${i + 1}`
            });
        }
        return data;
    }

    // 初始化图标管理器
    const billboardManager = new HighPerformanceBillboardManager(viewer);

    // DOM元素
    const addIconsBtn = document.getElementById('addIcons');
    const clearIconsBtn = document.getElementById('clearIcons');
    const addSingleIconBtn = document.getElementById('addSingleIcon');
    const flyToIconsBtn = document.getElementById('flyToIcons');
    const toggleIconsBtn = document.getElementById('toggleIcons');
    const toggleLabelsBtn = document.getElementById('toggleLabels');
    const iconCountElement = document.getElementById('iconCount');
    const loadingStatus = document.getElementById('loadingStatus');
    const successStatus = document.getElementById('successStatus');
    const bgOptions = document.querySelectorAll('.bg-option');

    // 更新图标计数显示
    function updateIconCount() {
        iconCountElement.textContent = billboardManager.getIconCount();
    }

    // 添加10000个图标
    addIconsBtn.addEventListener('click', async () => {
        addIconsBtn.disabled = true;
        loadingStatus.style.display = 'block';
        successStatus.textContent = '';

        setTimeout(async () => {
            const testData = generateTestData(10000);
            const result = await billboardManager.addBillboardsBatch(testData);

            loadingStatus.style.display = 'none';
            successStatus.textContent = `成功添加 ${result.count} 个图标+广告牌，耗时 ${result.time} 毫秒`;
            successStatus.className = 'success';

            updateIconCount();
            addIconsBtn.disabled = false;
        }, 100);
    });

    // 清除所有图标
    clearIconsBtn.addEventListener('click', () => {
        billboardManager.clearBillboards();
        successStatus.textContent = '已清除所有图标和广告牌';
        successStatus.className = '';
        updateIconCount();
    });

    // 添加单个图标
    addSingleIconBtn.addEventListener('click', () => {
        const singleData = {
            longitude: 116.39 + (Math.random() * 2 - 1),
            latitude: 39.91 + (Math.random() * 2 - 1),
            height: Math.random() * 1000,
            color: '#FF5722',
            iconText: '⭐',
            name: '特殊地点'
        };

        billboardManager.addSingleBillboard(singleData);
        successStatus.textContent = `已添加单个图标: ${singleData.name}`;
        successStatus.className = '';
        updateIconCount();
    });

    // 飞行到图标区域
    flyToIconsBtn.addEventListener('click', () => {
        viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(116.39, 39.91, 500000),
            duration: 2
        });
    });

    // 切换图标显示
    toggleIconsBtn.addEventListener('click', () => {
        const isActive = toggleIconsBtn.classList.contains('active');
        if (isActive) {
            toggleIconsBtn.classList.remove('active');
            billboardManager.toggleIconsVisibility(false);
        } else {
            toggleIconsBtn.classList.add('active');
            billboardManager.toggleIconsVisibility(true);
        }
    });

    // 切换广告牌显示
    toggleLabelsBtn.addEventListener('click', () => {
        const isActive = toggleLabelsBtn.classList.contains('active');
        if (isActive) {
            toggleLabelsBtn.classList.remove('active');
            billboardManager.toggleLabelsVisibility(false);
        } else {
            toggleLabelsBtn.classList.add('active');
            billboardManager.toggleLabelsVisibility(true);
        }
    });

    // 背景色选择
    bgOptions.forEach(option => {
        option.addEventListener('click', () => {
            // 移除所有active类
            bgOptions.forEach(opt => opt.classList.remove('active'));
            // 添加active类到当前选项
            option.classList.add('active');

            // 解析颜色值并更新
            const colorStr = option.getAttribute('data-color');
            const backgroundColor = Cesium.Color.fromCssColorString(colorStr);

            // 根据背景色自动选择文字颜色
            const textColor = this.getContrastTextColor(backgroundColor);

            billboardManager.updateLabelColors(backgroundColor, textColor);
        });
    });

    // 根据背景色获取对比文字颜色
    function getContrastTextColor(backgroundColor) {
        // 计算背景色的亮度
        const brightness = (backgroundColor.red * 299 + backgroundColor.green * 587 + backgroundColor.blue * 114) / 1000;
        // 如果背景色较亮，使用黑色文字，否则使用白色文字
        return brightness > 0.5 ? Cesium.Color.BLACK : Cesium.Color.WHITE;
    }

    // 初始更新图标计数
    updateIconCount();
</script>
</body>
</html>